﻿function SearchHandler() {
	var _this = this;
	this.searchBar = null;
	this.searchButton = null;
	this.searchInput = null;
	this.grid = null;
	
	this.search = function(search) {
		_this.grid.getDataRows().each(function() {
			$(this).css('display', '');
			$(this).find('td').removeClass('search-found');
			
			var rec = _this.grid.getRecord(this);
			var match = 0;
			for (var i=0;i<_this.grid.options.columns.length;i++) {
				var value = rec[_this.grid.options.columns[i].field];
				if (_this.grid.options.columns[i].renderer != null) {
					value = _this.grid.options.columns[i].renderer.renderValue(_this.grid.options.columns[i], rec);
				}
				var d = _this.grid.columnReferences.getKeyByValue(_this.grid.options.columns[i]);
				
				var cellIndex = $(d).index();
				
				if ((''+value).match(search)) {
					$(this.cells[cellIndex]).addClass('search-found');
					match++;;
				}
			}
			
			$(this).css('display',  match > 0 ? '': 'none');
		});
	};
	this.clear = function() {
		_this.grid.getDataRows().each(function() {
			$(this).css('display', '');
			$(this).find('td').removeClass('search-found');
		});
		if (this.searchInput != null) {
			this.searchInput.val('');
			this.searchButton.removeClass('selected');
		}
		_this.dirty = false;
	};

	this.detach = function() {
		//_this.grid.element.find('.search-bar').remove();
		_this.grid.removeToolbarWidget(this.searchBar);
		_this.grid.pageContentChanged.remove(_this.clear);
	};
	
	this.attach = function(grid) {
		this.grid = grid;
		this.searchBar = $('<span>').addClass('search-bar');
		this.searchInput = $('<input>').keyup(function(e) {
			_this.dirty = true;
			_this.searchButton.removeClass('selected');
			if (e.keyCode == 13) searchButton.click();
		});
		this.searchButton = $('<button>').html('Search').button({icons: {primary: "ui-icon-search"}}).click(function()  {
			alert('x');
			if (!$(this).hasClass('selected')) {
				if (_this.searchInput.val() == '') {
					_this.clear();
					return;
				}
				if (_this.dirty == true) {
					_this.search(_this.searchInput.val());
					$(this).addClass('selected');
				}
			} else {
				_this.clear();
				_this.searchInput.val('');
				$(this).removeClass('selected');
			}
			
			_this.grid.resize();
		});
		
		this.searchBar.append(this.searchInput);
		this.searchBar.append(this.searchButton);
		
		if (_this.grid.addToolbarWidget) _this.grid.addToolbarWidget(this.searchBar);
		_this.grid.pageContentChanged.add(_this.clear);
	};
}; SearchHandler.inherits(DatagridPlugin);